package com.tarena.luban.demo.gateway.error;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
@Order(-1) //有一个对象ResponseStatusExcetionHandler
@Component
@Slf4j
public class MyErrorExceptionHandler implements ErrorWebExceptionHandler {
    /**
     * 当前网关运行过程中 所有的过滤器 返回值Mono.error(exception)
     * @param exchange
     * @param ex
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        //TODO 把网关自己的内部过滤器 抛的异常 和自定义的业务异常区分开处理
        //所有异常 都返回给前端一个固定结构的数据
        ServerHttpResponse response = exchange.getResponse();
        log.info("当前网关出现的异常类型:{}",ex.getClass().getName());
        //乱码处理
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String result="{'code':'500','message':"+ex.getMessage()+"}";
        return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
            }
        }));
    }
}
